import { ADDPRODUCTTOCART, DECREMENTINVENTORY } from '../actionTypes'

const state = {
  items: []
}

const mutations = {
  setItems(state, product) {
    let result = state.items.find(p => p.id === product.id)
    if (result) {
      result.quantity++
    } else {
      state.items.push({
        ...product,
        quantity: 1
      })
    }
  }
}

const actions = {
  [ADDPRODUCTTOCART]({commit, dispatch}, product) {
    commit('setItems', product)
    // 减少库存
    dispatch(`product/${DECREMENTINVENTORY}`, product, {
      root: true
    })
  }
}

const getters = {
  totalprice(state) {
    return state.items.reduce((sum, product) => {
      sum += product.price * product.quantity
      return sum
    }, 0)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}